package com.txy.mvnSpringbootDemo01.controller;

import com.txy.mvnSpringbootDemo01.util.SignUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/demo")
public class DemoController {

    // http://localhost:8088/api/demo/hello?username=Tom&timestamp=1760346292930&sign=6ab55c6b0e4a4e7e1a693fb17b43dd9892901fda4a49176250a11995382a5926
    @GetMapping("/hello")
    public Map<String, Object> hello(
            @RequestParam String username,
            @RequestParam String timestamp,
            @RequestParam String sign
    ) {
        Map<String, Object> result = new HashMap<>();

        // 1. 校验时间戳（比如 5 分钟有效期）
        long now = System.currentTimeMillis();
        long reqTime = Long.parseLong(timestamp);
        if (Math.abs(now - reqTime) > 5 * 60 * 1000) {
            result.put("code", 401);
            result.put("msg", "请求过期");
            return result;
        }

        // 2. 校验签名
        // 构建参数
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("timestamp", timestamp);
        // 生成签名
        String expectedSign = SignUtil.generateSign(params);
        // 验证签名
        if (!expectedSign.equals(sign)) {
            result.put("code", 401);
            result.put("msg", "签名无效");
            return result;
        }

        // 3. 返回数据
        result.put("code", 200);
        result.put("msg", "签名验证成功");
        result.put("data", "Hello, " + username + "!");
        return result;
    }
}
